package com.han.controllers;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.han.bom.Professor;
import com.han.bom.Student;
import com.han.bom.User;
import com.han.dao.UserDAO;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private static Logger logger = Logger.getLogger(LoginServlet.class.getName());
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		logger.info("Entered LoginServlet GET");
		
		UserDAO userdao = new UserDAO();
		String username = request.getRemoteUser();
		
		User user=null;
		try {
			user = userdao.retrieveUserByUsername(username);
		} catch (ClassNotFoundException e1) {
			logger.error(e1.getMessage(), e1);
			e1.printStackTrace();
		} catch (SQLException e1) {
			logger.error(e1.getMessage(), e1);
			e1.printStackTrace();
		}
		
		if(user!=null){
			
			HttpSession session = request.getSession();
				
			if(user instanceof Student){
				
				Student student = (Student)user;
								
				session.setAttribute("student", student);
	
				response.sendRedirect("Student/Home.jsp");
				
			}else{
				
				Professor professor = (Professor)user;
				
				professor.setStudents(new ArrayList<Student>());
				
				session.setAttribute("professor", professor);
				
				response.sendRedirect("Professor/Home.jsp");		
			}
		}
		else{
			response.sendRedirect("Login.jsp?msg=Error&type=fail");
		}
			
		}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
